﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

namespace XFABManager
{
    public class FileTools
    {

        /// <summary>
        /// 复制一个文件夹
        /// </summary>
        /// <param name="sourceDir">源文件夹</param>
        /// <param name="destDir">目标文件夹</param>
        /// <param name="progress">进度改变的回调 第一个参数是正在复制的文件名称 第二个是复制的进度</param>
        /// <param excludeSuffix="excludeSuffix">不需要复制的文件的后缀</param>
        public static bool CopyDirectory(string sourceDir, string destDir, Action<string, float> progress,string[] excludeSuffix = null)
        {
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            if (!Directory.Exists(sourceDir))
            {
                Debug.LogError(string.Format(" 复制失败 ! 源目录{0}不存在! ", sourceDir));
                return false;
            }

            foreach (string folderPath in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories))
            {
                if (!Directory.Exists(folderPath.Replace(sourceDir, destDir)))
                    Directory.CreateDirectory(folderPath.Replace(sourceDir, destDir));
            }
            string[] files = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);
            //string filePath = null;
            for (int i = 0; i < files.Length; i++)
            {
                //filePath = files[i];
                if (excludeSuffix!=null && excludeSuffix.Length != 0) {
                    bool isContinue = false;
                    foreach (var item in excludeSuffix)
                    {
                        if (Path.GetExtension(files[i]).Equals(item)) {
                            isContinue = true;
                            Debug.LogFormat("跳过文件:{0} 后缀:{1} 过滤后缀:{2}", files[i], Path.GetExtension(files[i]), item);
                            break;
                        }
                    }
                    if (isContinue) continue; 
                }
                
                var fileDirName = Path.GetDirectoryName(files[i]).Replace("\\", "/");
                var fileName = Path.GetFileName(files[i]);
                string newFilePath = Path.Combine(fileDirName.Replace(sourceDir, destDir), fileName);

                progress?.Invoke(fileName, (float)(i + 1) / (float)files.Length);

                File.Copy(files[i], newFilePath, true);
            }

            return true;
        }

        /// <summary>
        /// 复制一个文件
        /// </summary>
        /// <returns></returns>
        public static CopyFileRequest Copy(string source, string des)
        {
            string key = string.Format("copy:{0}{1}", source, des);
            return AssetBundleManager.ExecuteOnlyOnceAtATime<CopyFileRequest>(key, () => {
                CopyFileRequest request = new CopyFileRequest();
                CoroutineStarter.Start(request.Copy(source, des));
                return request;
            });
        }

        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public static long GetDirectorySize(string dirPath)
        {
            if (!System.IO.Directory.Exists(dirPath))
                return 0;
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            //获取di目录中所有文件的大小
            foreach (System.IO.FileInfo item in di.GetFiles())
            {
                len += item.Length;
            }

            //获取di目录中所有的文件夹,并保存到一个数组中,以进行递归
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectorySize(dis[i].FullName);//递归dis.Length个文件夹,得到每隔dis[i]下面所有文件的大小
                }
            }
            return len;
        }


        /// <summary>
        /// 删除一个文件夹
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        public static void DeleteDirectory(string dirPath)
        {
            if (!System.IO.Directory.Exists(dirPath))
                return;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            di.Delete(true);
        }
        /// <summary>
        /// 删除指定目录下的文件以及文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void DeletePath(string path)
        {
            if (Directory.Exists(path))
            {
                DirectoryInfo info = new DirectoryInfo(path);
                FileSystemInfo[] arrInfo = info.GetFileSystemInfos();
                for (int i = 0; i < arrInfo.Length; ++i)
                {
                    if (arrInfo[i].Attributes == FileAttributes.Directory)
                    {
                        Directory.Delete(arrInfo[i].ToString(), true);
                    }
                    else
                    {
                        File.Delete(arrInfo[i].ToString());
                    }
                }
            }
        }
        /// <summary>
        /// 拷贝文件夹
        /// </summary>
        /// <param name="srcPath">需要被拷贝的文件夹路径</param>
        /// <param name="tarPath">拷贝目标路径</param>
        public static void CopyFolder(string srcPath, string tarPath)
        {
            if (!Directory.Exists(srcPath))
            {
                Debug.Log("CopyFolder is finish.");
                return;
            }

            if (!Directory.Exists(tarPath))
            {
                Directory.CreateDirectory(tarPath);
            }

            //获得源文件下所有文件
            List<string> files = new List<string>(Directory.GetFiles(srcPath));
            files.ForEach(f =>
            {
                string destFile = Path.Combine(tarPath, Path.GetFileName(f));
                File.Copy(f, destFile, true); //覆盖模式
            });

            //获得源文件下所有目录文件
            List<string> folders = new List<string>(Directory.GetDirectories(srcPath));
            folders.ForEach(f =>
            {
                string destDir = Path.Combine(tarPath, Path.GetFileName(f));
                CopyFolder(f, destDir); //递归实现子文件夹拷贝
            });
        }

        public static void CopyDirectoryFiles(string srcPath, string destPath)
        {
            try
            {　　　　DirectoryInfo dir = new DirectoryInfo(srcPath);　　　　FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath+"\\"+i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        CopyFolder(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                    }
                    else
                    {
                        File.Copy(i.FullName, destPath + "\\" + i.Name,true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }}
    }

}

